package model.textchatserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

public class RoomMessageHandler implements Runnable
{
	ArrayList< BufferedReader > mReaders = new ArrayList<BufferedReader>();
	ArrayList< BufferedWriter > mWriters;
	
	boolean conti = true;

	@Override
	public void run() 
	{
		
		int timer = 0;
		
		while( conti )
		{
			checkForInput();
			
			if ( timer > 40 )
			{
				checkWritersStatus();
				timer = 0;
			}
			else
			{
				timer++;
			}
			
			try 
			{
				Thread.sleep( 50 );
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
		}
	}

	
	private synchronized void checkForInput()
	{
		for (int i = 0; i < mReaders.size(); i++) 
		{
			BufferedReader reader = mReaders.get( i );
			try
			{
				if ( reader.ready() )
				{
					char[] buf = new char[1024*10];
					int bytesReaded = reader.read( buf );
					writeAll( buf, 0, bytesReaded );
				}
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	
	private void checkWritersStatus()
	{
		char[] mark = {0, '\n'};
		writeAll( mark, 0, 2 );
	}
	
	
	private void writeAll(char[] buf, int start, int end)
	{
		for (int i = 0; i < mWriters.size(); i++)
		{
			BufferedWriter writer = mWriters.get( i );
			try
			{
				writer.write( buf, 0, end );
				writer.flush();
			}
			catch (IOException e)
			{
				try
				{
					writer.close();
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
			}
		}
	}
	
	
//	@Override
	public synchronized void updateSocketsInfo(ArrayList<Socket> sockets) 
	{
		mReaders = new ArrayList<BufferedReader>();
		mWriters = new ArrayList<BufferedWriter>();
		for (int i = 0; i < sockets.size(); i++) 
		{
			Socket socket = sockets.get( i );
			try 
			{
				BufferedReader reader = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
				mReaders.add( reader );
				BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
				mWriters.add( writer );
				
			
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	public void end()
	{
		conti = false;
	}
}
